(()=> {
	
	const buildList = [
		{
			name: '爱森堡',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L2.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L2-.png',
			id: 1
		},
		{
			name: '花街区',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L1.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L1-.png',
			id: 2
		},
		{
			name: '蓝郡邸',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L3.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L3-.png',
			id: 3
		},
		{
			name: '时代城',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L5.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L5-.png',
			id: 4
		},
		{
			name: '甜心镇',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L4.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L4-.png',
			id: 5
		},
		{
			name: '世豪庭',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L6.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L6-.png',
			id: 6
		},
		{
			name: '锦绣苑',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L7.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L7-.png',
			id: 7
		},
		{
			name: '塞纳畔',
			img: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L8.png',
			img2: 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_L8-.png',
			id: 8
		}
	]
	
	
	let ele = {};
	ele.is_option = $('#is_option');
	ele.optionlist = $('#optionlist');
	// ele.li = $('#optionlist li');
	ele.put_into = $('#put_into');
	ele.qishu = $('#qishu');
	ele.renshu = $('#renshu');
	ele.jinbi = $('#jinbi');
	ele.modal_warn = $('#modal-warn');
	ele.modal_warn2 = $('#modal-warn2');
	ele.close_warn2 = $('#close-warn2');
	ele.close_warn = $('#close-warn');
	ele.list = $('#list');
	ele.touru = $('#touru');
	ele.t_left1 = $('#t_left1');
	ele.t_left2 = $('#t_left2');
	ele.daojishi = $('#daojishi');
	ele.btm1 = $('#btm1');
	ele.touBuild = $('#touBuild');
	// ele.jiangli = $('#jiangli');
	ele.shangqi = $('#shangqi');
	ele.modal_warn3 = $('#modal-warn3');
	ele.close_warn3 = $('#close-warn3');
	ele.addnum = $('#addnum');
	ele.iptnum = $('#iptnum');
	ele.jiannum = $('#jiannum');
	ele.dq_jinbi = $('#dq_jinbi');
	ele.touru_jinbi = $('#touru_jinbi');
	ele.confirm = $('#confirm');
	
	ele.close_warn.onclick = ()=> {
		closeMdl(ele.modal_warn)
	}
	ele.close_warn2.onclick = ()=> {
		closeMdl(ele.modal_warn2)
	}
	ele.close_warn3.onclick = ()=> {
		closeMdl(ele.modal_warn3)
	}
	
	
	is_open = false;
	let is_zt = '';
	var countdownInterval  //定时器
	var js
	
	// 本期已投入
	let bqytrList = ['0','0','0','0','0','0','0','0']
	
	let bqytrList2 = 0;
	
	let set_iskey = 0;
	
	// ele.is_option.onclick = () => {
	// 	is_open = !is_open;
	// 	if(is_open) {
	// 		ele.optionlist.style.display = 'block'
	// 	}else {
	// 		ele.optionlist.style.display = 'none'
	// 	}
	// }
	
	// 投入数量
	// for(let i = 0; i < ele.li.length; i++) {
	// 	ele.li[i].onclick = ()=> {
	// 		let num = ele.li[i].getAttribute('data');
	// 		// console.log(num);
	// 		ele.put_into.innerText = num;
	// 		ele.optionlist.style.display = 'none'
	// 	}
	// }
	
	let token = getCookie("token");
	// socket ws://rentwx.qunx.cc:2347   ws://fbsf.hfksh.cn:2347
	const wsuri = 'ws://ws.hfksh.cn:2347?token=' + token
	let socket = null
	var timer
	let list = ''
	let fangid = '';
	let fangidNow = '';
	let p_id = '';
	let touxiang = '';
	let balance = '';
	
	window.addEventListener('pageshow', function(event) {
	    //event.persisted属性为true时，表示当前文档是从往返缓存中获取
	    if(event.persisted) location.reload();  
	});
	
	 window.addEventListener('pagehide', function(event) {
	   socket.close()
	});
	
	intil();
	// 获取个人信息接口
	function intil() {
		getUserInfo((res) => {
		    // console.log(res);
		    ele.jinbi.innerHTML = res.diamond
			ele.dq_jinbi.innerHTML = res.diamond
			balance = res.diamond
			if(res.info == null) {
				touxiang = '../img/my/tx1';
			} else {
				if(res.info.head_pic == null) {
					touxiang = res.info.sex == 1 ? '../img/my/tx1.png' : '../img/my/tx2.png'
				} else {
					touxiang = IMG_DOMAIN + res.info.head_pic
				}
			}
			// console.log(touxiang);
		})
		
	}
	
	// closeMdl(ele.modal_warn);
	
	
	
	// 获取列表
	function getlist() {
	    let data = {
	        type: 'join',
	        data: {}
	    }
	    socket.send(JSON.stringify(data))
	}
	
	let startTime = '';
	let status = '';
	werewolfIndex();
	startWebSocket();
	// 获取首页信息
	function werewolfIndex(){
	    let token = getCookie("token");
	    ajax({
			url: API_PATH.WEREWOLF_INDEX,
			method: 'GET',
			header: {
				'Authorization': token
			},
			success: res => {
				if (res.code == 1) {
					is_zt = res.data.invest_status;
					if(res.data.last_result.visiting_id == 0) {
						ele.shangqi.style.display = 'none'
					}else {
						ele.shangqi.style.display = 'block'
						ele.shangqi.innerHTML = '上期小偷潜入了' + buildList[res.data.last_result.visiting_id - 1].name
					}
					ele.qishu.innerText = res.data.werewolf_detail.phase + '期'
					p_id = res.data.werewolf_detail.id
					ele.renshu.innerHTML = '<span>'+ res.data.join_num+'</span><p>/10</p>'
					drawinfo(res.data.werewolf_log)
					list = res.data.werewolf_log
					status = res.data.werewolf_detail.status;
					startTime = res.data.werewolf_detail.start_time;
					bqytrList2 = res.data.my_invest_sum;
					if(startTime > 0) {
						ele.t_left1.style.display = 'none'
						ele.t_left2.style.display = 'flex'
						daojishi(startTime)
					} else {
						ele.t_left1.style.display = 'block'
						ele.t_left2.style.display = 'none'
					}
	                // startWebSocket()
				}
			}
		});
	}
	
	// var opts = { reconnection: false, transports: ['websocket'], extraHeaders: { 'Authorization': 'Bearer xxxx' } } var ws = new WebSocket(serverWs, opts);
	// 链接websocket
	function startWebSocket() {
		
	    socket = new WebSocket(wsuri)
		
	    //监听消息接收事件
	    socket.addEventListener('message', onMessage)
	
	    //监听WebSocket连接事件
	    socket.addEventListener('open', onOpen)
	
	    //监听WebSocket异常事件
	    socket.addEventListener('error', onError)
	
	    //监听WebSockt关闭事件
	    socket.addEventListener('close', onClose)
	}
	
	//监听WebSocket连接事件
	function onOpen() {
		let token = getCookie("token");
	    let data = {
	        type: 'join',
			data: {},
	    }
	    socket.send(JSON.stringify(data))
	    heart()
	}
	
	// 设置心跳
	function heart() {
	    clearInterval(timer);
	    let data = {
	        type: "pong",
	        data:{}
	    }
	    timer = setInterval(() => {
	        // 传递参数给服务器
	        socket.send(JSON.stringify(data))
	    }, 30000)
	}
	
	//监听WebSocket异常事件
	function onError(e) {
	    console.error(e)
	    startWebSocket()
	}
	//监听消息接收事件
	function onMessage(e) {
	    if (!e) return
	    // console.log(e.data)
	    let data = JSON.parse(e.data)
	    // console.log(data)
	  
	    switch (data.type) {
	        case 'login': 
	            // getlist(); // 绑定用户 发送u_id
	            break;
	        case 'index':
	            // drawinfo(data.data.list) // 渲染列表
	            break;
	        case 'error':
	            openTips(data.msg)
				set_iskey = 0
	            break;
	        case 'list': // 投入完推给所有人
	            enroll(data.data)
	            break;
			case 'invest': // 投入成功
				openTips(data.msg)
				enterSuccess(data.data)
				break;
			case 'change_invest':
				openTips(data.msg)
				changeOk(data.data)
				break;
	        case 'werewolf_res': // 开局结果
				// werewolf_res 游戏结果(data.status==2 流局 data.status==3结束 data.visiting_id袭击的建筑 data.result_sum瓜分的金币)
	            result(data.data)
	            break;
	        case 'game_start':
				gameAction(data)
	            break;
	        case 'back':
	            openTips(data.msg)
	            // drawinfo(list)
	            break;
	    }
	}
	
	// gameAction(1688702193)
	
	//监听WebSockt关闭事件
	function onClose(e) {
	    console.log('WebSocket disconnected.', e)
	}
	
	// removeCookie('buildid');
	// console.log(getCookie('buildid'));
	function result(data) {
		if(data.status == 3) {
			// console.log(data,data.result_sum);
			ele.touBuild.innerHTML = '小偷光顾了'+buildList[data.visiting_id - 1].name+'，其他人保住财产，平分<img src="http://img.qxgs.cc/tiantianlaishouzu/img/home/jinbi.png" alt=""><span>'+data.result_sum +'奖励</span>'
			setTimeout(()=> {
				closeMdl(ele.modal_warn);
				openMdl(ele.modal_warn2);
				closeMdl(ele.modal_warn3);
				intil();
				werewolfIndex();
				ele.t_left1.style.display = 'flex'
				ele.t_left2.style.display = 'none'
				removeCookie('buildid');
				setCookie('buildid','')
				// console.log(getCookie('buildid'),fangidNow);
				// fangidNow = 0;
				fangid = 0;
			},2000)
		}else if(data.status == 2){
			openTips('本局流局，请玩家重新投入！')
			location.reload(true);
			fangid = 0;
		}
	}
	
	
	// 报名成功改变状态
	function enroll(data) {
		ele.renshu.innerHTML = '<span>'+ data.join_num +'</span><p>/10</p>'
		let _data = data.list
	    let html = '';
		for(let i = 0; i < _data.length; i++) {
			let j = i + 1;
			html += `<div class="apart apart${j}">
						<img class="wode" src="../img/battle/MG_WD.png" alt="">
						<p>${buildList[i].name}</p>
						<img class="bulidimg" src="${buildList[i].img}" alt="">
						<div class="hall hall${j}">
							<img class="renimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_XH.png" alt="">
							<span>${_data[i].people_num}</span>
							<img class="jinimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/home/jinbi.png" alt="">
							<span>${_data[i].invest_sum}</span>
						</div>
					</div>`;
			// bqytrList[i] = _data[i].my_invest_sum;
		}
		
	    ele.list.innerHTML = html;
		
		let aparts = $('.apart');
		let bulidimgs = $('.bulidimg');
		let renimgs = $('.renimg');
		let wodes = $('.wode');
		// 选投 转投
		for(let i = 0; i < aparts.length ; i++) {
			aparts[i].onclick = (e)=> {
				let that = e.target
				for(let j = 0; j < aparts.length ; j++) {
					let id = j+1;
					if(that == bulidimgs[j]) {
						fangidNow = id;
						setCookie('buildid',fangidNow)
						bulidimgs[j].src = buildList[i].img2
						renimgs[j].src = touxiang
						wodes[j].style.display = 'block';
					}else {
						bulidimgs[j].src = buildList[j].img
						renimgs[j].src = 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_XH.png'
						wodes[j].style.display = 'none';
					}
				}
			}
		}
		
		let buillid = getCookie('buildid');
		// console.log(buillid);
		if(buillid) {
			bulidimgs[buillid - 1].src = buildList[buillid - 1].img2
			renimgs[buillid - 1].src = touxiang
			wodes[buillid - 1].style.display = 'block';
		}
	    // daojishi()
	    // clearInterval(js)
	}
	
	// 修改参与人数
	function numchange(data) {
		ele.renshu.innerHTML = '<span>'+ data.join_num+'</span><p>/10</p>'
	}
	
	function enterSuccess(data) {
		let aparts = $('.apart');
		let bulidimgs = $('.bulidimg');
		let renimgs = $('.renimg');
		let wodes = $('.wode');
		setCookie('buildid',data.building_id);
		fangid = data.building_id;
		is_zt = 1;
		ele.jinbi.innerHTML = data.diamond
		ele.dq_jinbi.innerHTML = data.diamond
		balance = data.diamond
		// bqytrList[data.building_id - 1] = data.my_invest_sum;
		bqytrList2 = data.my_invest_sum;
		// intil();
		// werewolfIndex();
		closeMdl(ele.modal_warn3);
		
		fangidNow = data.building_id;
		bulidimgs[data.building_id - 1].src = buildList[data.building_id - 1].img2
		renimgs[data.building_id - 1].src = touxiang
		wodes[data.building_id - 1].style.display = 'block';
		
		set_iskey = 0;
		
	}
	
	// 渲染列表
	function drawinfo(data) {
	    let html = ''
	    for (let i = 0; i < data.length; i++) {
	        let d = data[i];
			let j = i + 1;
			html += `<div class="apart apart${j}">
						<img class="wode" src="../img/battle/MG_WD.png" alt="">
						<p>${buildList[i].name}</p>
						<img class="bulidimg" src="${buildList[i].img}" alt="">
						<div class="hall hall${j}">
							<img class="renimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_XH.png" alt="">
							<span>${data[i].people_num}</span>
							<img class="jinimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/home/jinbi.png" alt="">
							<span>${data[i].invest_sum}</span>
						</div>
					</div>`;
			bqytrList[i] = data[i].my_invest_sum;
			bqytrList2 = data[i].my_invest_sum;
	    }
	    ele.list.innerHTML = html;
		
		let aparts = $('.apart');
		let bulidimgs = $('.bulidimg');
		let renimgs = $('.renimg');
		let wodes = $('.wode');
		
		// 退出重进
		for (let i = 0; i < data.length; i++) {
			if(data[i].invest_status == 1) {
				fangid = data[i].building_id
				fangidNow = data[i].building_id
				// console.log(fangid,fangidNow);
				bulidimgs[parseInt(data[i].building_id) - 1].src = buildList[parseInt(data[i].building_id) - 1].img2
				renimgs[parseInt(data[i].building_id) - 1].src = touxiang
				wodes[parseInt(data[i].building_id) - 1].style.display = 'block';
			}
		}
		// 选投 转投
		for(let i = 0; i < aparts.length ; i++) {
			aparts[i].onclick = (e)=> {
				let that = e.target
				for(let j = 0; j < aparts.length ; j++) {
					let id = j+1;
					if(that == bulidimgs[j]) {
						fangidNow = id;
						bulidimgs[j].src = buildList[i].img2
						renimgs[j].src = touxiang
						wodes[j].style.display = 'block';
					}else {
						bulidimgs[j].src = buildList[j].img
						renimgs[j].src = 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_XH.png'
						wodes[j].style.display = 'none';
					}
				}
			}
		}
	}
	
	ele.touru.onclick = () => {
		if(is_zt == 1) {
			// console.log(fangid,fangidNow);
			if(fangid != fangidNow) {
				// 转投
				// werewolfChangeInvest(p_id,fangidNow);
				let data = {
					type: 'change_invest',
					data: {
						p_id: p_id,
						new_building_id: fangidNow
					},
				}
				// set_iskey = 1
				socket.send(JSON.stringify(data))
			} else {
				let num = ele.put_into.innerText;
				ele.iptnum.value = ele.put_into.innerText;
				console.log(fangid,fangidNow);
				if(!fangidNow || fangidNow == 0) {
					openTips('请先选择要投入的建筑')
				} else {
					ele.touru_jinbi.innerHTML = bqytrList2;
					openMdl(ele.modal_warn3)
				}
			}
		}  else {
				let num = ele.put_into.innerText;
				ele.iptnum.value = ele.put_into.innerText;
				console.log(fangid,fangidNow);
				if(fangidNow == fangid) {
					openTips('请先选择要投入的建筑!')
				} else {
					ele.touru_jinbi.innerHTML = bqytrList2;
					openMdl(ele.modal_warn3)
				}
			}
	}
	
	ele.addnum.onclick = ()=> {
		let num = ele.iptnum.value
		num++;
		if(num > balance) {
			openTips('金币不足')
			ele.iptnum.value = balance;
		} else {
			ele.iptnum.value = num;
		}
	}
	
	ele.jiannum.onclick = ()=> {
		let num = ele.iptnum.value
		num--;
		if(num <= 0) {
			openTips('投入金币不能小于0')
			ele.iptnum.value = 1;
		} else {
			ele.iptnum.value = num;
		}
	}
	
	ele.iptnum.oninput = (e)=> {
		// console.log(e);
		// console.log(balance,ele.iptnum.value);
		if(parseInt(ele.iptnum.value) > balance) {
			openTips('不能大于持有金币数量')
			ele.iptnum.value = balance
		} else if(ele.iptnum.value < 0) {
			openTips('最小数量为1')
			ele.iptnum.value = 1
		} else if(!/^\\d+$/.test(ele.iptnum.value)) {
			ele.iptnum.value = parseInt(ele.iptnum.value)
		}
	}
	
	ele.confirm.onclick = () => {
		// let num = ele.put_into.innerText;
		let num = ele.iptnum.value;
		if(set_iskey == 0) {
			console.log(fangid,fangidNow);
			if(is_zt == 1) {
				if(fangid == fangidNow) {
					if(fangid == '') {
						openTips('请选择要投入的建筑')
					}else {
						// 投入
							let data = {
							    type: 'invest',
								data: {
									p_id: p_id,
									invest_num: num,
									building_id: fangid
								},
							}
							set_iskey = 1
							socket.send(JSON.stringify(data))
					}
				} else {
					// 转投
					let data = {
						type: 'change_invest',
						data: {
							p_id: p_id,
							new_building_id: fangidNow
						},
					}
					set_iskey = 1
					socket.send(JSON.stringify(data))
					// werewolfChangeInvest(p_id,fangidNow);
				}
			} else {
				// 投入
				if(fangidNow == '') {
					openTips('请选择要投入的建筑')
				} else {
					let data = {
					    type: 'invest',
						data: {
							p_id: p_id,
							invest_num: num,
							building_id: fangidNow
						},
					}
					set_iskey = 1
					socket.send(JSON.stringify(data))
				}
			}
		}
		
	}
	
	// // 投入金币
	// function werewolfInvest(p_id,num,id){
	//     let token = getCookie("token");
	//     ajax({
	// 		url: API_PATH.WEREWOLF_INVEST,
	// 		method: 'POST',
	// 		header: {
	// 			'Authorization': token
	// 		},
	// 		data: {
	// 			p_id: p_id,
	// 			invest_num: num,
	// 			building_id: id
	// 		},
	// 		success: res => {
	// 			if (res.code == 1) {
	// 				openTips(res.msg)
	// 			} else {
	// 				openTips(res.msg || '未知错误')
	// 			}
	// 		}
	// 	});
	// }
	
	// 投入金币 转投
	function werewolfChangeInvest(p_id,id){
	    let token = getCookie("token");
	    ajax({
			url: API_PATH.WEREWOLF_CHANGE_INVEST,
			method: 'POST',
			header: {
				'Authorization': token
			},
			data: {
				p_id: p_id,
				new_building_id: id
			},
			success: res => {
				if (res.code == 1) {
					// console.log(fangid,fangidNow);
					fangid = fangidNow;
					let aparts = $('.apart');
					let bulidimgs = $('.bulidimg');
					let renimgs = $('.renimg');
					let wodes = $('.wode');
					setCookie('buildid',id);
					openTips(res.msg)
					for(let i = 0; i < aparts.length ; i++) {
						bulidimgs[i].src = buildList[i].img
						wodes[i].style.display = 'none'
						renimgs[i].src = 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_XH.png'
						bulidimgs[parseInt(id) - 1].src = buildList[id - 1].img2
						renimgs[parseInt(id) - 1].src = touxiang
						wodes[parseInt(id) - 1].style.display = 'block'
					}
					bulidimgs[parseInt(id) - 1].src = buildList[id - 1].img2
					renimgs[parseInt(id) - 1].src = touxiang
					wodes[parseInt(id) - 1].style.display = 'block'
					closeMdl(ele.modal_warn3);
					// werewolfIndex();
				} else {
					openTips(res.msg || '未知错误')
				}
			}
		});
	}
	
	//  转投成功
	function changeOk(data) {
		fangid = fangidNow;
		setCookie('buildid',fangidNow);
		let aparts = $('.apart');
		let bulidimgs = $('.bulidimg');
		let renimgs = $('.renimg');
		let wodes = $('.wode');
		for(let i = 0; i < aparts.length ; i++) {
			bulidimgs[i].src = buildList[i].img
			wodes[i].style.display = 'none'
			renimgs[i].src = 'http://img.qxgs.cc/tiantianlaishouzu/img/battle/MG_XH.png'
			bulidimgs[fangidNow - 1].src = buildList[fangidNow - 1].img2
			renimgs[fangidNow - 1].src = touxiang
			wodes[fangidNow - 1].style.display = 'block'
		}
		bulidimgs[fangidNow - 1].src = buildList[fangidNow - 1].img2
		renimgs[fangidNow - 1].src = touxiang
		wodes[fangidNow - 1].style.display = 'block'
		closeMdl(ele.modal_warn3);
	}
	
	
	
	function gameAction(data) {
		ele.t_left1.style.display = 'none'
		ele.t_left2.style.display = 'flex'
		daojishi(data.start_time)
	}
	
	// 进行倒计时
	function daojishi(time) {
	    let daojishi = $('#daojishi');
	    // 每秒钟更新一次倒计时
	    clearInterval(countdownInterval)
	    countdownInterval = setInterval(() => {
	        countdown(time)
	    }, 1000)
	}
	
	// 倒计时逻辑
	function countdown(time) {
	    let daojishi = $('#daojishi');
	    // 当前时间戳（单位：毫秒）
	    let currentTimestamp = new Date().getTime();
	    // 计算剩余时间（单位：毫秒）
	    let remainingTime = (time * 1000 + 60000) - currentTimestamp;
	    var remainingSeconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
	   
	    // 更新倒计时元素内容
	    daojishi.innerHTML = remainingSeconds
		if(remainingSeconds <= 0) {
			clearInterval(countdownInterval);
			daojishi.innerHTML = 0
			openMdl(ele.modal_warn)
		}
	}
	
	
	
})()